package com.studyyoun.android.nonghe.share;

import android.graphics.*;
import android.graphics.Bitmap.*;
import android.text.*;

import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.welcom.App;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import java.io.*;

/**
 * Created by androidlongs on 17/6/15.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

public class WeixinShareFunction {
    public final IWXAPI api=WeixinMainFunction.getInstance().api;

    private WeixinShareFunction (){


    }
    private static class QQMainFunctionSingle{
        private static WeixinShareFunction sQQMainFunction = new WeixinShareFunction();
    }

    public static WeixinShareFunction getInstance(){
        return QQMainFunctionSingle.sQQMainFunction;
    }

    public enum ShareType{
        MSG,//消息
        FIND,//朋友圈
        COLLE//收藏
    }

    public void shareWebFunction(WinxinSharModel model ,ShareType shareType){
        WXWebpageObject wxWebpageObject = new WXWebpageObject();
        if (TextUtils.isEmpty(model.webUrl)){
            model.webUrl="http://www.studyyoun.com/";
        }
        wxWebpageObject.webpageUrl = model.webUrl;



        WXMediaMessage mediaMessage = new WXMediaMessage(wxWebpageObject);

        mediaMessage.title = model.title;

        mediaMessage.description = model.description;

        mediaMessage.thumbData=bmpToByteArray(BitmapFactory.decodeResource(App.getInstance().getResources(), R.mipmap.app_icon),false);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = mediaMessage;
        if (shareType==ShareType.MSG){
            req.scene = SendMessageToWX.Req.WXSceneSession;
        }else if (shareType==ShareType.FIND){
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }else {
            req.scene = SendMessageToWX.Req.WXSceneFavorite;
        }

        WeixinMainFunction.getInstance().api.sendReq(req);
    }









    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(CompressFormat.PNG, 80, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

}
